﻿/// <reference path="backbone-min.js" />
/// <reference path="jquery-1.8.2.min.js" />
/// <reference path="underscore-min.js" />
/// <reference path="app.js" />
/// <reference path="../exclude/sp.js" />
'use strict';

var Bk = Backbone;
//viewed lists models

var ViewedListsModel = Bk.Model.extend({
    siteUrl: null,
    listName: null,
    description: null,
    itemCount: null,
    imageUrl: null,
    selected: false,
    initialize: function ()
    {
        //_.bindAll(this, "onSelected");
        this.bind('change:selected', this.onSelected);
    },
    ///after change the selected property, update the page status.
    onSelected: function (model, value, target)
    {
        this.set({ selected: value });
        $(target.target).toggleClass("selected");
    }
});

var ViewedListsModels = Bk.Collection.extend({
    isLoaded : false,
    model: ViewedListsModel,
    clear: function (options)
    {
        options || (options = {});
        while (this.length > 0) {
            this.at(0).destroy(options);
        }
        if (!options.silent) this.trigger('clear', this, options);
        return this;
    },
    save: function (onSuccess, onFail)
    {
        UpdateConfiguredSettings(this, 'ViewedLists', onSuccess, onFail);
    }
});
//end viewed lists models

//chart types models
var ChartTypesModel = Bk.Model.extend({
    chartType: null,
    displayText:null,
    description: null,
    overViewImage: null,
    selected: false,
    initialize: function () {
        //_.bindAll(this, "onSelected");
        this.bind('change:selected', this.onSelected);
    },
    ///after change the selected property, update the page status.
    onSelected: function (model, value, options) {
        if (options) {
            this.set({ selected: value });
            if (value) {
                $("#" + options.chartType).addClass("selected");
                this.set({ chartType: options.chartType });
            }
            else {
                $("#"+options.chartType).removeClass("selected");
            }
        }
    }
});

var ChartTypesModels = Bk.Collection.extend({
    model: ChartTypesModel,
    isLoaded: false,
    isInitialize: true,
    comparator : function(model) { 
        return !model.get("selected");
    },
    initialize: function () {
        if (this.isInitialize) {
            var areaType = new ChartTypesModel();
            areaType.set({
                chartType: 'area',
                displayText: 'Area Charts',
                description: 'Area Chart emphasizes changes in values by filling in the portion of the graph beneath the line that connects each data point in a series.',
                overViewImage: '../Images/ChartTypes/area.png',
                //selected: false
            }, { chartType: "area" });
            this.add(areaType);

            var barType = new ChartTypesModel();
            barType.set({
                chartType: 'bar',
                displayText: 'Bar Charts',
                description: 'Show value changes over time, or illustrate a quantitative comparison of multiple entities.',
                overViewImage: '../Images/ChartTypes/bar.png',
                //selected: false
            }, { chartType: "bar" });
            this.add(barType);

            var bubbleType = new ChartTypesModel();
            bubbleType.set({
                chartType: 'bubble',
                displayText: 'Bubble Charts',
                description: 'A Scatter chart variation that allows to display three types of data along x- and y-axis using size of bubbles as third dimension.',
                overViewImage: '../Images/ChartTypes/bubble.png',
                //selected: false
            }, { chartType: "bubble" });
            //this.add(bubbleType);

            var donutType = new ChartTypesModel();
            donutType.set({
                chartType: 'donut',
                displayText: 'Donut Charts',
                description: 'Donut chart is a Pie chart variation, with the ability to support multiple series.',
                overViewImage: '../Images/ChartTypes/donut.png',
                //selected: false
            }, { chartType: "donut" });
            this.add(donutType);

            var lineType = new ChartTypesModel();
            lineType.set({
                chartType: 'line',
                displayText: 'Line Charts',
                description: 'Show trends in data over regular intervals, or show trends among multiple entities.',
                overViewImage: '../Images/ChartTypes/line.png',
                //selected: false
            }, { chartType: "line" });
            this.add(lineType);

            var pieType = new ChartTypesModel();
            pieType.set({
                chartType: 'pie',
                displayText: 'Pie Charts',
                description: 'Show the relative quantitative value or percentage of items with respect to the total.',
                overViewImage: '../Images/ChartTypes/pie.png',
                //selected: false
            }, { chartType: "pie" });
            this.add(pieType);

            var scatterType = new ChartTypesModel();
            scatterType.set({
                chartType: 'scatter',
                displayText: 'Scatter Charts',
                description: 'Show the relationship of multiple values or entities, often grouped by category or relationship, along a common x- and y-axis.',
                overViewImage: '../Images/ChartTypes/scatter.png',
                //selected: false
            });
            //this.add(scatterType);

            var stockType = new ChartTypesModel();
            stockType.set({
                chartType: 'stock',
                displayText: 'Stock Charts',
                description: 'A combination of Line and Candlestick chart representing historical stock prices.',
                overViewImage: '../Images/ChartTypes/stock.png',
                //selected: false
            });
            //this.add(stockType);

            var radialGaugeType = new ChartTypesModel();
            radialGaugeType.set({
                chartType: 'radialGauge',
                displayText: 'Radial Gauge',
                description: 'Show range or progress data in a radial (circular or semi-circular) view.',
                overViewImage: '../Images/ChartTypes/radial-gauge.png',
                //selected: false
            });
            //this.add(radialGaugeType);
        }
    },
    save: function (onSuccess, onFail) {
        UpdateConfiguredSettings(this, chartTypeFieldName, onSuccess, onFail);
    }
});

//end chart types models

//begin list field models
var ChartListItemsModel = Bk.Model.extend({
    xFieldName: null,
    sortFieldOrder: null,
    yField: null
});

var ChartXAxisModel = Bk.Model.extend({
    fieldName: null,
    aggregateFunction: null,
    seriesName: null
});

var ChartXAxisModels = Bk.Collection.extend({
    model:ChartXAxisModel
});

var ListFiledModel = Bk.Model.extend({
    itemTitle: null,
    itemInternalName:null
});

var ListFields = Bk.Collection.extend({
    model: ListFiledModel,
    listName: null,
    initialize: function (options) {
        if (options && options.listName) {
            this.listName = options.listName;
        }
    },
    isExist: function (value) {
        var exist = false;
        this.each(function(theModel){
            if (theModel.itemTitle == value) {
                exist = true;
                return false;
            }
        });
        return exist;
    },
    loadFields: function (onSuccess, onFail)
    {
        if (this.listName) {
            //load all listItems.
            var site = context.get_site();
            var web = site.get_rootWeb();
            context.load(web);
            var configurationList = web.get_lists().getByTitle(this.listName);
            var fields = configurationList.get_fields();
            context.load(fields);
            var self = this;
            context.executeQueryAsync(function (sender, e) {
                var enumerator = fields.getEnumerator();
                var IgnoreFieldInternalName = [ "AppAuthor", "AppEditor" ];
                while (enumerator.moveNext()) {
                    var field = enumerator.get_current();
                    if (field.get_hidden() ||
                        $.inArray(IgnoreFieldInternalName, field.get_internalName()) > 0 ||
                        self.isExist(field.get_title())) { continue; }
                    var listItemModel = new ListFiledModel();
                    listItemModel.set({ itemTitle: field.get_title(), itemInternalName: field.get_internalName() });
                    listItemModel.itemTitle = field.get_title();
                    listItemModel.itemInternalName = field.get_internalName();

                    self.add(listItemModel);
                }
                if (onSuccess) onSuccess();
            }, function (sender, e) {
                App.ErrorMessage = e.get_message();
                App.ErrorInEzEditView.render();
            });
        }
    }
});
//end list field models

//configuration model
var ConfigurationModel = Bk.Model.extend({
    xAxis: { filedName: null, sortName: null },
    yAxis: { fieldNames: [], aggregateFunction: [], seriesName: [] },
    save: function (onSuccess, onFail) {
        UpdateConfiguredSettings(this, chartConfigurationFieldName, onSuccess, onFail);
    }
});

//end configuration model

//chart model
var ChartModel = Bk.Model.extend({
    title: { text: 'Chart App' },
    legend: {
        position:'bottom'
    },
    seriesDefaults: {
        type: 'area'
    },
    series: [],
    categoryAxis: {
        categories: [],
        majorGridLines: {
            visible:false
        }
    }
});
//end chart model

var ChartConfigurationModel = Bk.Model.extend({
    back: null,
    showBack: false,
    configurationInfo: null,
    initialize: function () {
        //_.bindAll(this, "onSelected");
        this.bind('change:back', this.onBackChanged);
        this.bind('change:showBack', this.onShowBackChanged);
        this.bind('change:configurationInfo', this.onConfigurationInfoChanged)
    },

    onBackChanged: function () {
        var backUrl = this.get('back');
        if (backUrl.indexOf('#') != -1)
        {
            $('#headBackbutton').attr('href', this.get('back'));
        }
        else
        {
            $('#headBackbutton').attr('href', '#/' + this.get('back'));
        }
    },

    onShowBackChanged: function () {
        if (this.get('showBack')) {
            $('#headBackbutton').show(500);
        }
        else {
            $('#headBackbutton').hide(500);
        }
        //$('#headBackbutton').css('display', this.get('showBack') ? 'block' : 'none');
    },

    onConfigurationInfoChanged: function () {
        $('#configurationInfo').text(this.get('configurationInfo'));
    }
});

function UpdateConfiguredSettings(collection, fieldName,onSuccess,onFail) {
    clearNotifycation();
    showNotifycation("Woring on it...");
    var query = new SP.CamlQuery();
    var web = context.get_web();
    var configurationList = web.get_lists().getByTitle(configurationListName);
    var items = configurationList.getItems(query);
    context.load(items);
    context.executeQueryAsync(Function.createDelegate(this, onLoadConfigurationListItems), null);
    function onLoadConfigurationListItems(senader, e) {
        var item = items.get_item(0);
        if (item) {
            item.set_item(fieldName, JSON.stringify(collection));
            item.update();
            context.executeQueryAsync(Function.createDelegate(this, onSuccess), Function.createDelegate(this, onFail));
        }
        else {
            var ListItem = configurationList.addItem(new SP.ListCreationInformation());
            ListItem.set_item(fieldName, JSON.stringify(collection));
            ListItem.update();
            context.executeQueryAsync(Function.createDelegate(this, onSuccess), Function.createDelegate(this, onFail));
        }
    }
}